package nuc.edu.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import nuc.edu.tlias.mapper.EmpExprMapper;
import nuc.edu.tlias.mapper.EmpMapper;
import nuc.edu.tlias.pojo.*;
import nuc.edu.tlias.service.EmpLogService;
import nuc.edu.tlias.service.EmpService;
import nuc.edu.tlias.utils.JwtUtils;
import org.apache.ibatis.javassist.expr.NewArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    private static final Logger log = LoggerFactory.getLogger(EmpServiceImpl.class);
    @Autowired
    EmpMapper empMapper;
    @Autowired
    EmpExprMapper empExprMapper;

    @Autowired
    EmpLogService empLogService;
    /*
    //原始分页方法
    @Override
    public PageResult<Emp> page(@RequestParam Integer page, @RequestParam Integer pageSize) {

        Long total = empMapper.count();
        Integer start = (page-1)*pageSize;
        List<Emp> rows = empMapper.list(start, pageSize);
        return new PageResult<Emp>(total,rows);
    }*/
    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        log.info("======================================={}",empQueryParam);
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());

        // 查询数据
        List<Emp> empList = empMapper.list(empQueryParam);

        // 获取分页信息
        Page<Emp> p = (Page<Emp>) empList;

        // 返回封装好的分页结果
        return new PageResult<Emp>(p.getTotal(),p.getResult());


    }

    @Override
    public List<Emp> findall() {
        List<Emp> list;
        list = empMapper.findall();
        return list;
    }

    @Transactional
    @Override
    public void save(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insert(emp);

            List<EmpExpr> exprList =emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)){
                exprList.forEach(empExpr -> {
                    empExpr.setEmpId(emp.getId());
                });

                empExprMapper.insertBatch(exprList);
            }
        }  finally {
            //记录操作日志
            EmpLog empLog = new EmpLog(null,LocalDateTime.now(),"新增员工："+emp);
            empLogService.insertLog(empLog);
        }


    }
    @Transactional
    @Override
    public void delete(Integer[] ids) {
        empMapper.deleteByIds(ids);
        empExprMapper.deleteByEmpIds(ids);
    }

    @Override
    public Emp findById(Integer id) {
        Emp emp = empMapper.findById(id);
        return emp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);

        empExprMapper.deleteByEmpIds(Arrays.asList(emp.getId()).toArray(new Integer[0]));
        log.info("{}",Arrays.asList(emp.getId()).toArray(new Integer[0]));

        List<EmpExpr> list = emp.getExprList();

        if (!CollectionUtils.isEmpty(list)){
            list.forEach(empExpr -> empExpr.setEmpId(emp.getId()));

            empExprMapper.insertBatch(list);
        }

    }

    @Override
    public LoginInfo login(Emp emp) {

        Emp e = empMapper.login(emp);

        if (e!=null){

            Map<String,Object> claims = new HashMap<>();
            claims.put("id",e.getId());
            claims.put("username",e.getUsername());

            String jwt = JwtUtils.generateJwt(claims);

            System.out.println("登录成功");
            return new LoginInfo(e.getId(),e.getUsername(),e.getName(),jwt);

        }
        return null;
    }
}
